#include <func.h>

// 客户端

typedef struct
{
    char file_name[64];
} fileName_t;

int recvn(int netfd, void *buf, int length);

int main(void)
{
    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(sock_fd == -1)
        error(1, errno, "socket");    

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi("8080"));
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    if(connect(sock_fd, (struct sockaddr*)&addr, sizeof(addr)) == -1)
        error(1, errno, "connect");
    
    // 接收文件名
    fileName_t file_name;
    recvn(sock_fd, &file_name, sizeof(file_name));
    printf("file: %s\n", file_name.file_name);

    struct stat statbuf;
    recvn(sock_fd, &statbuf, sizeof(statbuf));
    printf("size = %ld\n", statbuf.st_size);

    off_t size = statbuf.st_size;
    int file_fd = open(file_name.file_name, O_RDWR | O_CREAT | O_TRUNC, 0666);

    if(ftruncate(file_fd, size) == -1)
        error(1, errno, "ftruncate");
    
    while(1)
    {
        char buf[1024] = {0};
        int count = recvn(sock_fd, buf, sizeof(buf));
        printf("count = %d\n", count);
        if(count == 0)
            break;
        write(file_fd, buf, count);
    }

    system("sha1sum a.mp4");
    close(sock_fd);
    close(file_fd);
    return 0;
}

int recvn(int netfd, void *buf, int length)
{
    // 读到的字节数
    int count = 0;
    // 还需要读的字节数
    int sum = length;
    // 下次写入的位置
    char* p = (char*)buf;
    while(1)
    {
        int ret = recv(netfd, p, sum, 0);
        if(ret == 0)
            break;

        p += ret;
        count += ret;
        sum -= ret;
    }

    return count;
}
